/* sha512.c
**
** Copyright (c) 2007, Meadhbh S. Hamrick
** All rights reserved.
** 
** Redistribution  and  use  in  source  and  binary  forms,  with  or  without
** modification, are permitted provided that the following conditions are met:
** 
**  * Redistributions of  source code must  retain the above  copyright notice,
**    this list of conditions and the following disclaimer.
** 
**  * Redistributions in binary form must reproduce the above copyright notice,
**    this list of conditions and the following disclaimer in the documentation
**    and/or other materials provided with the distribution.
** 
**  * Neither the  name of  Project Meadhbh  nor the names of  its contributors
**    may be used  to endorse  or promote  products derived from this  software
**    without specific prior written permission.
** 
** THIS SOFTWARE IS PROVIDED BY  THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY  EXPRESS OR IMPLIED WARRANTIES,  INCLUDING, BUT NOT  LIMITED TO, THE
** IMPLIED WARRANTIES  OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR PURPOSE
** ARE DISCLAIMED.  IN NO  EVENT SHALL THE  COPYRIGHT OWNER OR  CONTRIBUTORS BE
** LIABLE  FOR  ANY  DIRECT,   INDIRECT,  INCIDENTAL,  SPECIAL,  EXEMPLARY,  OR
** CONSEQUENTIAL  DAMAGES  (INCLUDING,  BUT  NOT  LIMITED  TO,  PROCUREMENT  OF
** SUBSTITUTE GOODS  OR SERVICES;  LOSS OF USE,  DATA, OR PROFITS;  OR BUSINESS
** INTERRUPTION)  HOWEVER CAUSED  AND ON  ANY THEORY  OF LIABILITY,  WHETHER IN
** CONTRACT,  STRICT LIABILITY,  OR  TORT (INCLUDING  NEGLIGENCE OR  OTHERWISE)
** ARISING IN ANY WAY  OUT OF THE USE OF THIS SOFTWARE,  EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.
** 
** $Id: sha512.c 48 2007-08-30 21:49:44Z msh.mobile $
*/

/** \file sha512.c
 ** This file implements the SHA512 cryptographic hash function.
 */

/* Macro Definitions */

#ifndef MC_ROTATE_LEFT
#define MC_ROTATE_LEFT(x,n,b) (((x)<<(n))|((x)>>(b-n)))
#endif

#ifndef MC_ROTATE_RIGHT
#define MC_ROTATE_RIGHT(x,n,b) (((x)>>(n))|((x)<<(b-n)))
#endif

#ifndef MC_SHIFT_RIGHT
#define MC_SHIFT_RIGHT(x,n) ((x)>>(n))
#endif

#define MC_MIC_SHA512_CH(x,y,z) ( ( ( x ) & ( y ) )^ ( (~(x) ) & ( z ) ) )
#define MC_MIC_SHA512_MA(x,y,z) ( ( ( x ) & ( y ) ) ^ ( ( x ) & ( z ) ) ^ ( ( y ) & ( z ) ) )
#define MC_MIC_SHA512_BS0(x) ((MC_ROTATE_RIGHT((x),28,64))^(MC_ROTATE_RIGHT((x),34,64))^(MC_ROTATE_RIGHT((x),39,64)))
#define MC_MIC_SHA512_BS1(x) ((MC_ROTATE_RIGHT((x),14,64))^(MC_ROTATE_RIGHT((x),18,64))^(MC_ROTATE_RIGHT((x),41,64)))
#define MC_MIC_SHA512_LS0(x) ((MC_ROTATE_RIGHT((x),1,64))^(MC_ROTATE_RIGHT((x),8,64))^(MC_SHIFT_RIGHT(x,7)))
#define MC_MIC_SHA512_LS1(x) ((MC_ROTATE_RIGHT((x),19,64))^(MC_ROTATE_RIGHT((x),61,64))^(MC_SHIFT_RIGHT(x,6)))


/* File Includes */
#include "mutil.h"
#include "mcrypto/sha512.h"

/* Static Prototypes */

static void mc_mic_sha512_transform( tMCSha512 *context );

/* Static Variables */

static uint64_t mc_mic_sha512_constants[80] = {
  0x428A2F98D728AE22LL, 0x7137449123EF65CDLL, 0xB5C0FBCFEC4D3B2FLL, 0xE9B5DBA58189DBBCLL,
  0x3956C25BF348B538LL, 0x59F111F1B605D019LL, 0x923F82A4AF194F9BLL, 0xAB1C5ED5DA6D8118LL,
  0xD807AA98A3030242LL, 0x12835B0145706FBELL, 0x243185BE4EE4B28CLL, 0x550C7DC3D5FFB4E2LL,
  0x72BE5D74F27B896FLL, 0x80DEB1FE3B1696B1LL, 0x9BDC06A725C71235LL, 0xC19BF174CF692694LL,
  0xE49B69C19EF14AD2LL, 0xEFBE4786384F25E3LL, 0x0FC19DC68B8CD5B5LL, 0x240CA1CC77AC9C65LL,
  0x2DE92C6F592B0275LL, 0x4A7484AA6EA6E483LL, 0x5CB0A9DCBD41FBD4LL, 0x76F988DA831153B5LL,
  0x983E5152EE66DFABLL, 0xA831C66D2DB43210LL, 0xB00327C898FB213FLL, 0xBF597FC7BEEF0EE4LL,
  0xC6E00BF33DA88FC2LL, 0xD5A79147930AA725LL, 0x06CA6351E003826FLL, 0x142929670A0E6E70LL,
  0x27B70A8546D22FFCLL, 0x2E1B21385C26C926LL, 0x4D2C6DFC5AC42AEDLL, 0x53380D139D95B3DFLL,
  0x650A73548BAF63DELL, 0x766A0ABB3C77B2A8LL, 0x81C2C92E47EDAEE6LL, 0x92722C851482353BLL,
  0xA2BFE8A14CF10364LL, 0xA81A664BBC423001LL, 0xC24B8B70D0F89791LL, 0xC76C51A30654BE30LL,
  0xD192E819D6EF5218LL, 0xD69906245565A910LL, 0xF40E35855771202ALL, 0x106AA07032BBD1B8LL,
  0x19A4C116B8D2D0C8LL, 0x1E376C085141AB53LL, 0x2748774CDF8EEB99LL, 0x34B0BCB5E19B48A8LL,
  0x391C0CB3C5C95A63LL, 0x4ED8AA4AE3418ACBLL, 0x5B9CCA4F7763E373LL, 0x682E6FF3D6B2B8A3LL,
  0x748F82EE5DEFB2FCLL, 0x78A5636F43172F60LL, 0x84C87814A1F0AB72LL, 0x8CC702081A6439ECLL,
  0x90BEFFFA23631E28LL, 0xA4506CEBDE82BDE9LL, 0xBEF9A3F7B2C67915LL, 0xC67178F2E372532BLL,
  0xCA273ECEEA26619CLL, 0xD186B8C721C0C207LL, 0xEADA7DD6CDE0EB1ELL, 0xF57D4F7FEE6ED178LL,
  0x06F067AA72176FBALL, 0x0A637DC5A2C898A6LL, 0x113F9804BEF90DAELL, 0x1B710B35131C471BLL,
  0x28DB77F523047D84LL, 0x32CAAB7B40C72493LL, 0x3C9EBE0A15C9BEBCLL, 0x431D67C49C100D4CLL,
  0x4CC5D4BECB3E42B6LL, 0x597F299CFC657E2ALL, 0x5FCB6FAB3AD6FAECLL, 0x6C44198C4A475817LL
};

void mc_mic_sha512_clone( tMCSha512 *new_context, tMCSha512 *old_context ) {
  memcpy( new_context, old_context, sizeof( tMCSha512 ) );
}

/** \fn tMCErr mc_mic_sha512_clear( tMCSha512 *context )
**  \brief clear sensitive data from the context
*/
void mc_mic_sha512_clear( tMCSha512 *context ) {
  mc_mic_sha512_initialize( context );
}

/** \fn tMCErr mc_mic_sha512_initialize( tMCSha512 *context )
**  \brief initialize a SHA512 context to it's initial condition
*/
void mc_mic_sha512_initialize( tMCSha512 *context ) {
  context->count = 0;

  memset( context->data.asChar, 0, 640 );

  context->state[0] = 0x6A09E667F3BCC908LL;
  context->state[1] = 0xBB67AE8584CAA73BLL;
  context->state[2] = 0x3C6EF372FE94F82BLL;
  context->state[3] = 0xA54FF53A5F1D36F1LL;
  context->state[4] = 0x510E527FADE682D1LL;
  context->state[5] = 0x9B05688C2B3E6C1FLL;
  context->state[6] = 0x1F83D9ABFB41BD6BLL;
  context->state[7] = 0x5BE0CD19137E2179LL;
}
 
/** \fn tMCErr mc_mic_sha512_update( tMCSha512 *context, uint8_t *data, uint32_t length )
**  \brief provide input to the hash function
*/

void mc_mic_sha512_update( tMCSha512 *context, uint8_t *data, uint32_t length ) {
  uint64_t input_index;
  uint64_t block_index;

  for( input_index = 0; input_index < (uint64_t) length; input_index ++ ) {

    /* copy data into the buffer */
    block_index = context->count % 128;
    context->data.asChar[ block_index ] = data[ input_index ];

    /* update the counter */
    context->count++;

    /* if the block buffer is full, transform the data */
    if( 127 == block_index ) {
      mc_mic_sha512_transform( context );
    }
  }
}

/** \fn tMCErr mc_mic_sha512_digest( tMCSha512 *context, uint8_t *digest )
**  \brief get the digest of the data provided
*/
void mc_mic_sha512_digest( tMCSha512 *context, uint8_t *digest ) {
  uint64_t next_pad_index;
  uint64_t i;

  /* where does the first padding byte go? */
  next_pad_index = ( context->count % 128 );

  /* put the first padding byte */
  context->data.asChar[ next_pad_index++ ] = 0x80;

  /* are we past the 112th byte in the data buffer? */

  if( next_pad_index > 111 ) {
    mc_mic_sha512_transform( context );
    next_pad_index = 0;
  }

  for( ; next_pad_index < 112; next_pad_index++ ) {
    context->data.asChar[ next_pad_index ] = 0;
  }

  /* append count to block */

  /* todo: find a platform independent way of doing a hton on long longs */
  context->data.asLongLong[ 15 ] = MU_HTON64(context->count * 8);

  /* call transform */

  mc_mic_sha512_transform( context );

  /* we may have to change state endianness */

#ifndef WORDS_BIGENDIAN
  for( i=0; i<8; i++ ) {
    context->state[i] = MU_HTON64( context->state[i] );
  }
#endif

  /* copy state to digest */
  memcpy( digest, (uint8_t *) context->state, 64 );
}

/** \fn void mc_mic_sha512_transform( tMCSha512 *context )
**  \brief "churn" the internal state of the SHA512 context based on input data
*/
static void mc_mic_sha512_transform( tMCSha512 *context ) {
  uint64_t local_state[8];
  uint64_t t1, t2;
  uint32_t i;

  /* depending on the endianness of the processor, we may have to change */
  /* the endianness of the data array                                    */

#ifndef WORDS_BIGENDIAN
  for( i = 0; i < 16; i++ ) {
    context->data.asLongLong[i] = ( uint64_t ) MU_HTON64( context->data.asLongLong[i] );
  }
#endif

  /* Prepare the Message Schedule */
  /* note: the update and digest calls already place the first 16 words of
  ** the message in the data member.
  */
  for( i=16; i<80; i++ ) {
    context->data.asLongLong[ i ] = (uint64_t) (
      MC_MIC_SHA512_LS1( context->data.asLongLong[ i - 2 ] ) +
      context->data.asLongLong[ i - 7 ] +
      MC_MIC_SHA512_LS0( context->data.asLongLong[ i - 15] ) +
      context->data.asLongLong[ i - 16] );
  }

  /* Initialize Working Variables */

  local_state[ 0 ] = context->state[ 0 ];
  local_state[ 1 ] = context->state[ 1 ];
  local_state[ 2 ] = context->state[ 2 ];
  local_state[ 3 ] = context->state[ 3 ];
  local_state[ 4 ] = context->state[ 4 ];
  local_state[ 5 ] = context->state[ 5 ];
  local_state[ 6 ] = context->state[ 6 ];
  local_state[ 7 ] = context->state[ 7 ];

  for( i = 0; i < 80; i++ ) {
    t1 = (uint64_t) (
      local_state[7] + MC_MIC_SHA512_BS1( local_state[4] ) +
      MC_MIC_SHA512_CH( local_state[4], local_state[5], local_state[6] ) +
      mc_mic_sha512_constants[ i ] +
      context->data.asLongLong[ i ] );
    t2 = (uint64_t) (
      MC_MIC_SHA512_BS0( local_state[0] ) +
      MC_MIC_SHA512_MA( local_state[0], local_state[1], local_state[2] ) );
    local_state[7] = local_state[6];
    local_state[6] = local_state[5];
    local_state[5] = local_state[4];
    local_state[4] = local_state[3] + t1;
    local_state[3] = local_state[2];
    local_state[2] = local_state[1];
    local_state[1] = local_state[0];
    local_state[0] = t1 + t2;
  }

  /* add the local_state back into the context state */
  context->state[ 0 ] += local_state[ 0 ];
  context->state[ 1 ] += local_state[ 1 ];
  context->state[ 2 ] += local_state[ 2 ];
  context->state[ 3 ] += local_state[ 3 ];
  context->state[ 4 ] += local_state[ 4 ];
  context->state[ 5 ] += local_state[ 5 ];
  context->state[ 6 ] += local_state[ 6 ];
  context->state[ 7 ] += local_state[ 7 ];

  memset( context->data.asChar, 0, 640);
}
